/*
 * 2014-10-25 <br/>
 *
 * Copyright (c) 1994-1999 AnHui LonSun, Inc. <br/>
 * All rights reserved.	<br/>
 *
 * This software is the confidential and proprietary information of AnHui	<br/>
 * LonSun, Inc. ("Confidential Information").  You shall not	<br/>
 * disclose such Confidential Information and shall use it only in	<br/>
 * accordance with the terms of the license agreement you entered into	<br/>
 * with Sun. <br/>
 */
package cn.bs.socket.client;

import cn.bs.socket.server.Dgram;

import java.io.IOException;
import java.net.*;

import static cn.bs.socket.server.Dgram.toDataGram;

public class DatagramSocketClient implements Runnable {
    static int port = 7200;
    private byte[] buf = new byte[1000];
    private DatagramPacket dp = new DatagramPacket(buf, buf.length);
    private DatagramSocket socket;

    private InetAddress address;
    private int id;

    public DatagramSocketClient(int identifier) throws UnknownHostException, SocketException {
        socket = new DatagramSocket();
        id = identifier;
        address = InetAddress.getByName(null);
    }
    @Override
    public void run() {

        try {
            for(int k=0;k<25;k++){
                String msg = "Client-" + id + ":msg-" + k;
                System.out.println(address.getHostName());
                socket.send(toDataGram(msg, InetAddress.getLocalHost(), port));

                socket.receive(dp);
                String rcvd = "Client #" + id +
                        ", rcvd from " +
                        dp.getAddress() + ", " +
                        dp.getPort() + ": " +
                        Dgram.toString(dp);
                System.out.println(rcvd);

            }
            socket.close();


        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
